<template>
  <px-drawer v-model="visible" @open="openDrawer" @close="closeDrawer">
    <template #header>
      <h3 style="font-weight: bold">{{ typeTitle }}</h3>
    </template>
    <template #default>
      <px-form ref="formRef" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <EquipClassSelect :className="formValue.className" @changeClassName="changeClassName" :isDisabled="drawerType === 'addChild'" />
        <px-form-item label="种类" prop="category">
          <px-select v-model="formValue.category" filterable clearable placeholder="请选择种类">
            <px-option v-for="item in categoryList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="父级类型名称" prop="parentId">
          <px-tree-select
            v-model="formValue.parentId"
            placeholder="请选择父级类型名称"
            filterable
            clearable
            :data="typeList"
            check-strictly
            node-key="id"
            :default-expanded-keys="[0]"
            :disabled="drawerType === 'addChild'"
            :render-after-expand="false"
            :props="defaultProps"
            @current-change="handlePrarentChange"
            @visible-change="queryTypeList"
          />
        </px-form-item>
        <px-form-item label="类型名称" prop="name">
          <px-input v-model="formValue.name" placeholder="请输入类型名称" maxlength="50" clearable />
        </px-form-item>
        <px-form-item label="排序" prop="sort">
          <px-input-number v-model="formValue.sort" :min="0" controls-position="right" />
        </px-form-item>
      </px-form>
    </template>
    <template #footer>
      <px-button @click="closeDrawer">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </template>
  </px-drawer>
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { saveSparePartType, updateSparePartType, queryListTree_1 } from "@/api/equip/spareParts";
import { PxMessage } from "px-ui";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { computed, reactive, ref, toRefs } from "vue";

// 调用父级-关闭抽屉、查询列表方法
const emits = defineEmits(["closeDrawer", "queryTable"]);
// 父级传过来的值
const props = defineProps(["visible", "drawerType", "typeTitle", "sparePartsRow", "treeData"]);
const visible = computed(() => props.visible);
// 页面本身的值
// 树形选择图
const defaultProps = {
  children: "children",
  label: "name",
  value: "id"
};
const formRef = ref();
const initFormValue = {
  id: "",
  className: "",
  category: "",
  parentId: "",
  name: "",
  sort: 0
};
const state = reactive<any>({
  formValue: initFormValue,
  categoryList: [],
  typeList: [],
  newId: ""
});
const { formValue, categoryList, typeList, newId } = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  className: [{ required: true, message: "科室不能为空", trigger: ["blur", "change"] }],
  category: [{ required: true, message: "种类不能为空", trigger: ["blur", "change"] }],
  name: [{ required: true, message: "类型名称不能为空", trigger: ["blur", "change"] }]
}));

// 科室组件调用父组件
const changeClassName = val => {
  formValue.value.className = val;
  formValue.value.parentId = "";
};
// 打开抽屉
const openDrawer = () => {
  formRef.value.resetFields();
  querycategorySelect();
  queryTypeList(true);
  if (props.drawerType === "add") {
    formValue.value = { ...initFormValue, ...props.sparePartsRow };
  } else if (props.drawerType === "edit") {
    formValue.value = { ...props.sparePartsRow };
    newId.value = formValue.value.id;
  } else {
    formValue.value = { ...initFormValue, ...props.sparePartsRow };
    newId.value = formValue.value.id;
  }
};
const handlePrarentChange = val => {
  formValue.value.sort = val?.children?.length ?? 0;
  if (val.id !== 0) {
    formValue.value.className = val?.className;
    formValue.value.category = val?.category;
  }
};
// 种类类下拉框
const querycategorySelect = async () => {
  categoryList.value = [];
  const params = {
    typeCode: "typeCategory"
  };
  const data = await queryDictData(params);
  categoryList.value = data;
};
// 类型下拉框
const queryTypeList = async flag => {
  if (flag) {
    const data = await queryListTree_1({ className: formValue.value.className });
    const treeData = [{ name: "根节点", id: 0, children: data }];
    if (props.drawerType === "addChild" || props.drawerType === "edit") {
      typeList.value = filterTree(treeData, [newId.value]);
    } else {
      typeList.value = treeData;
    }
  } else {
    typeList.value = [];
  }
};
// 提交按钮
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const { id, parentId, name, category, className, sort } = formValue.value;
      const params = { id, parentId, name, category, className, sort };
      if (props.drawerType === "edit") {
        await updateSparePartType(params);
        PxMessage.success("编辑成功");
        emits("closeDrawer");
        emits("queryTable");
      } else {
        await saveSparePartType(params);
        PxMessage.success("新增成功");
        emits("closeDrawer");
        emits("queryTable");
      }
    }
  });
};
// 关闭抽屉
const closeDrawer = () => {
  formRef.value.resetFields();
  newId.value = "";
  emits("closeDrawer");
};
const filterTree = (tree, idsToRemove) => {
  // 将需要删除的ID数组转换为Set提高查找效率
  const removeSet = new Set(idsToRemove);

  // 递归过滤函数
  function filterNode(node) {
    // 如果当前节点在删除列表中，直接返回null（删除整个子树）
    if (removeSet.has(node.id)) {
      return null;
    }

    // 浅拷贝当前节点（避免修改原始数据）
    const newNode = { ...node };

    // 递归处理子节点
    if (newNode.children && newNode.children.length) {
      newNode.children = newNode.children.map(child => filterNode(child)).filter(child => child !== null); // 过滤掉已删除的节点
    }

    return newNode;
  }

  // 处理整个树并返回过滤后的新树
  return tree.map(node => filterNode(node)).filter(node => node !== null);
};
</script>
<style lang="scss" scoped>
:deep(.px-select) {
  width: 100%;
}
</style>
